package org.lib.mysqlhello.tcache.try1;

import java.util.Objects;

import org.lib.mysqlhello.tcache.try1.dto.AddDTO;
import org.lib.mysqlhello.tcache.try1.dto.UpdateDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

/**
 * 服务实现类：BookServiceImpl（基于MySQL）
 * @author ben
 * @date 2021-08-26 10:39:17 CST
 */
@Service
@Slf4j
public class BookServiceImpl implements BookService {
	
	@Autowired
	private BookDao bookDao;
	
	private final static String BOOK_CACHE_VALUE = "mysql-hello";
	// key 的 单引号 必须有！
	private final static String BOOK_CACHE_KEY = "'book'";
	
	@Override
	@CacheEvict(value=BOOK_CACHE_VALUE, key=BOOK_CACHE_KEY)
	public Book add(AddDTO dto) {
		Book newbook = new Book(dto.getName(), dto.getAuthor());
		Book savedBook = bookDao.save(newbook);
		log.info("新增书：id={}", savedBook.getId());
		return savedBook;
	}

	@Override
	@CacheEvict(value = BOOK_CACHE_VALUE, key="'book_' + #id")
	public Boolean del(Long id) {
		bookDao.deleteById(id);
		return bookDao.existsById(id);
	}

	@Override
	@CachePut(value=BOOK_CACHE_VALUE, key="'book_' + #dto.getId()")
	public Book update(UpdateDTO dto) {
		Long id = dto.getId();
		if (Objects.isNull(id)) {
			return null;
		}
		
		Book oldBook = bookDao.findById(id).orElse(null);
		if (Objects.isNull(oldBook)) {
			return null;
		}
		
		oldBook.setSales(oldBook.getSales() + dto.getSalesIncr());
		Book savedBook = bookDao.save(oldBook);
		
		return savedBook;
	}

	@Override
	// 必须使用unless
	@Cacheable(value=BOOK_CACHE_VALUE, key="'book_' + #id", unless="#result == null")
	public Book findById(Long id) {
		if (Objects.isNull(id)) {
			return null;
		}
		return bookDao.findById(id).orElse(null);
	}

}
